package fun.codedesign.yixin.work.client.feign.config;

import java.util.function.Function;
import java.util.function.Supplier;

import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.client.circuitbreaker.ConfigBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import fun.codedesign.yixin.work.client.feign.QuestionAnswerFeignClientFallback;
import fun.codedesign.yixin.work.client.feign.QuestionAnswerFeignClientFallbackFactory;

@Configuration(proxyBeanMethods = false)
public class QuestionFeignClientConfiguration {

    @Bean
    public QuestionAnswerFeignClientFallback questionAnswerFeignClient() {
        return new QuestionAnswerFeignClientFallback();
    }

    @Bean
    public QuestionAnswerFeignClientFallbackFactory questionAnswerFeignClientFallbackFactory() {
        return new QuestionAnswerFeignClientFallbackFactory();
    }

    
    @SuppressWarnings("rawtypes")
    @Bean
    public CircuitBreakerFactory circuitBreakerFactory() {

        return new CircuitBreakerFactory() {
            @Override
            public CircuitBreaker create(String id) {
                System.out.println("---CircuitBreaker create---");
                return new CircuitBreaker() {

                    @Override
                    public <T> T run(Supplier<T> toRun, Function<Throwable, T> fallback) {
                        try {
                            return toRun.get();
                        } catch (Exception e) {
                            System.out.println("---fallback invoke---:" + fallback);
                            return fallback.apply(e);
                        }
                    }
                };
            }

            @Override
            protected ConfigBuilder configBuilder(String id) {
                return Object::new;
            }

            @Override
            public void configureDefault(Function defaultConfiguration) {

            }
        };
    }
}
